using NPOI.XSSF.UserModel;
using NPOI.SS.UserModel;
using WebApi.Core.Interfaces;
using Microsoft.Extensions.Hosting;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using NPOI.HSSF.UserModel;

namespace WebApi.Infrastructure.Services
{
    public class FileService : IFileService
    {
        private readonly IHostEnvironment _hostEnvironment;

        public FileService(IHostEnvironment hostEnvironment)
        {
            _hostEnvironment = hostEnvironment;
        }

        public async Task<Stream> GenerateExcelReport()
        {
            var workbook = new XSSFWorkbook();
            var sheet = workbook.CreateSheet("Report");

            // 创建标题行
            var headerRow = sheet.CreateRow(0);
            headerRow.CreateCell(0).SetCellValue("ID");
            headerRow.CreateCell(1).SetCellValue("Name");
            headerRow.CreateCell(2).SetCellValue("Value");

            // 添加示例数据
            for (int i = 1; i <= 10; i++)
            {
                var row = sheet.CreateRow(i);
                row.CreateCell(0).SetCellValue(i);
                row.CreateCell(1).SetCellValue($"Item {i}");
                row.CreateCell(2).SetCellValue(i * 100);
            }

            // 自动调整列宽
            for (int i = 0; i < 3; i++)
            {
                sheet.AutoSizeColumn(i);
            }

            // 将工作簿写入内存流
            var ms = new MemoryStream();
            workbook.Write(ms, true);
            ms.Position = 0;
            
            // 不要关闭 MemoryStream，让调用者负责关闭
            workbook.Close();
            return await Task.FromResult(ms);
        }

        public async Task<Stream> GenerateFromTemplate(string templateName)
        {
            // 构建模板文件的完整路径
            var templatePath = Path.Combine(_hostEnvironment.ContentRootPath, "templates", templateName);
            
            if (!File.Exists(templatePath))
            {
                throw new FileNotFoundException($"Template file not found: {templateName}");
            }

            XSSFWorkbook workbook;
            // 使用 using 块确保文件流被正确关闭
            using (var fs = new FileStream(templatePath, FileMode.Open, FileAccess.Read))
            {
                workbook = new XSSFWorkbook(fs);
            }

            var sheet = workbook.GetSheetAt(0);

            // 处理模板内容
            var currentDate = DateTime.Now.ToString("yyyy-MM-dd");
            
            // 查找并替换占位符
            for (int rowIndex = 0; rowIndex <= sheet.LastRowNum; rowIndex++)
            {
                var row = sheet.GetRow(rowIndex);
                if (row == null) continue;

                for (int cellIndex = 0; cellIndex < row.LastCellNum; cellIndex++)
                {
                    var cell = row.GetCell(cellIndex);
                    if (cell == null) continue;

                    if (cell.CellType == CellType.String)
                    {
                        switch (cell.StringCellValue)
                        {
                            case "{DATE}":
                                cell.SetCellValue(currentDate);
                                break;
                            case "{NO}":
                                cell.SetCellValue($"NO.{DateTime.Now:yyyyMMddHHmmss}");
                                break;
                        }
                    }
                }
            }

            // 添加数据
            var dataStartRow = 5;
            var data = await GetSampleData();

            foreach (var item in data)
            {
                var row = sheet.CreateRow(dataStartRow++);
                row.CreateCell(0).SetCellValue(item.Id);
                row.CreateCell(1).SetCellValue(item.Name);
                //row.CreateCell(2).SetCellValue(item.Value);
            }

            // 将修改后的工作簿写入新的内存流
            var ms = new MemoryStream();
            workbook.Write(ms, true);
            ms.Position = 0;
            
            // 关闭工作簿，但保持流开放
            workbook.Close();
            return ms;
        }

        private async Task<List<SampleData>> GetSampleData()
        {
            return await Task.FromResult(Enumerable.Range(1, 5)
                .Select(i => new SampleData
                {
                    Id = i,
                    Name = $"Sample Item {i}",
                    Value = i * 1000
                })
                .ToList());
        }

        private class SampleData
        {
            public int Id { get; set; }
            public string Name { get; set; }
            public decimal Value { get; set; }
        }

        public async Task<bool> UploadExcel(IFormFile file)
        {
            if (file == null || file.Length == 0)
                return false;

            try
            {
                var fileExt = Path.GetExtension(file.FileName).ToLower();
                if (fileExt != ".xlsx" && fileExt != ".xls")
                    return false;

                // 确保上传目录存在
                var uploadPath = Path.Combine(_hostEnvironment.ContentRootPath, "uploads");
                if (!Directory.Exists(uploadPath))
                {
                    Directory.CreateDirectory(uploadPath);
                }

                // 生成唯一文件名
                var fileName = $"{DateTime.Now:yyyyMMddHHmmss}_{Guid.NewGuid():N}{fileExt}";
                var filePath = Path.Combine(uploadPath, fileName);

                // 保存文件
                using (var stream = new FileStream(filePath, FileMode.Create))
                {
                    await file.CopyToAsync(stream);
                }

                // 读取Excel内容进行验证
                using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
                {
                    var workbook = fileExt == ".xlsx" ? 
                        new XSSFWorkbook(fs) : (IWorkbook)new HSSFWorkbook(fs);
                    
                    // 这里可以添加Excel内容的验证逻辑
                    
                    workbook.Close();
                }

                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }
    }
} 